package com.supermap.business.fileupload;

import com.alibaba.fastjson.JSONObject;
import com.supermap.dataservice.util.ImageUtil;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "file")
public class FileUploadController {

    @RequestMapping(value = "multiImgUpload")
    @ResponseBody
    public String multiFileUpload(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest;
        if (request instanceof ShiroHttpServletRequest) {
            ShiroHttpServletRequest shiroRequest = (ShiroHttpServletRequest) request;
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
            multipartRequest = commonsMultipartResolver.resolveMultipart((HttpServletRequest) shiroRequest.getRequest());

        } else {
            multipartRequest = (MultipartHttpServletRequest) request;
        }


        List<MultipartFile> files = new ArrayList<>();
        boolean flag = true;
        int count = 0;
        while (flag) {
            String img = "img" + count;
            List<MultipartFile> tmpFiles = multipartRequest.getFiles(img);
            if (tmpFiles != null && tmpFiles.size() > 0) {
                files.addAll(tmpFiles);
                count++;
            } else {
                flag = false;
            }
        }
        Integer type = Integer.valueOf(request.getParameter("type"));
        JSONObject result = new JSONObject();
        List<String> images = new ArrayList<String>();
        String img;
        for (MultipartFile file : files) {
            String filePath = "static";
            img = ImageUtil.saveImg(file, filePath, getTypeStr(type));
            if (img != null) {
                images.add(img);
            }
        }
        result.put("data", images);
        return result.toJSONString();
    }

    private String getTypeStr(Integer type) {
        if (1 == type) {
            return "img/agriculture";
        }
        if (2 == type) {
            return "img/disaster";
        }
        if (3 == type) {
            return "img/advisory";
        }
        if (4 == type) {
            return "img/header";
        }
        if (5 == type) {
            return "img/farming";
        }
        return "img/normal";
    }
}
